﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperKit
{
    public class ImageSizeGroupItem {
        public Size Size { get; }
        public List<FileInfo> Files { get; }
        public string Name { get; }
        public int Count => Files.Count;

        public ImageSizeGroupItem(Size size) {
            Size = size;
            Files = new List<FileInfo>();
            Name = string.Format("{0}x{1}", size.Width, size.Height);
        }
    }
    public class ImageSizeFile : ThreadToolItem {
        public Size size { get; set; }
        public FileInfo file { get; set; }

        public ImageSizeFile(FileInfo file) {
            this.file = file;
            size = Size.Empty;
        }

        public override void Process() {
            if (!Kit.IsFileType(file, Kit.PROCESSED_IMG_EXTS)) {
                size = Size.Empty;
                return;
            }

            try {
                var img = Image.FromFile(file.FullName);
                size = img.Size;
                img.Dispose();
            } catch (Exception) {
                size = new Size(1, 1);
            }
            
      
        }

        public override string ToString() {
            return file.Name;
        }
    }

    public class ImageSizeGroup {
        public FileGroup Group { get; }
        public int Count => Group.Count;
        public List<ImageSizeGroupItem> Items { get; }
        public ThreadTool<ImageSizeFile> Files { get; }


        public ImageSizeGroup(FileGroup group, int threadCount, GeneralOutput output) {
            Group = group;
            Items = new List<ImageSizeGroupItem>();
            Files = new ThreadTool<ImageSizeFile>(threadCount, output);
            foreach (var i in Group.Files) {
                Files.Add(new ImageSizeFile(i));
            }
        }

        public void Analysis() {
            Files.Start(null);

            for (int i = 0; i < Count; i++) {
                AddTo(Files.Items[i]);
            }
        }

        

        private void AddTo(ImageSizeFile item) {
            var group = GetGroup(item.size);
            if (group == null) {
                group = new ImageSizeGroupItem(item.size);
                Items.Add(group);
            }
            group.Files.Add(item.file);
        }

        private ImageSizeGroupItem GetGroup(Size size) {
            foreach (var i in Items) {
                if (i.Size == size) {
                    return i;
                }
            }
            return null;
        }

    }
}
